package com.fzu.thirdpartyservice.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fzu.commonutil.util.ApiException;
import com.fzu.thirdpartyservice.config.OssProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author yjl
 * @Description 文章上传工具类
 * @Version 1.0
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class FileUtil {
    private final OssProperties properties;

    public String upload(MultipartFile file) {
        long size = file.getSize()/1024/1024;
        if (size > 20) {
            throw new ApiException("文件大小不能超过20MB");
        }
        try {
            // 1.获取上传文件的输入流
            InputStream inputStream = file.getInputStream();
            // 2.获取文件名称
            String filename = file.getOriginalFilename();

            // 3.在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid + filename;

            // 4.创建一个与OSS服务器的链接
            OSS ossClient = new OSSClientBuilder().build(properties.getEndPoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());

            // 5.调用oss方法实现上传(Bucket名称,传到oss文件路径和文件名称,上传文件输入流)
            ossClient.putObject(properties.getBucketName(), filename, inputStream);

            // 6.返回文件路径
            return "https://" + properties.getBucketName()+"."+ properties.getEndPoint() +"/" + filename;
        } catch (IOException e) {
            log.error("【文件上传失败】:{}", e.getMessage());
            throw new ApiException("上传文件失败");
        }
    }


}
